package com.javaear.beangenerator.render;

import com.javaear.beangenerator.Beaner;
import com.javaear.beangenerator.ContextHolder;
import com.javaear.beangenerator.tools.IOUtils;
import com.javaear.beangenerator.tools.StringUtils;

import java.io.File;

/**
 * raise beaners and write its to Files
 *
 * @author aooer
 */
abstract class AbstractRender extends ContextHolder implements Render {

    /**
     * render beaners to files
     *
     * @param params params
     */
    public void render(String params) {
        Beaner beaner = raiseBeaner(params);
        try {
            IOUtils.write(beaner.toString(), destPath(beaner.getBeanName(), packageName(), destDir()));
            if (!embedStyle() && null != beaner.getChildren())
                for (Beaner child : beaner.getChildren())
                    IOUtils.write(child.toString(), destPath(child.getBeanName(), packageName(), destDir()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * file absolute path
     *
     * @param beanName    beanName
     * @param packageName packageName
     * @param destDir     destDir
     * @return filePath
     */
    private static String destPath(String beanName, String packageName, String destDir) {
        return destDir
                .concat(StringUtils.isEmpty(packageName) ? "" : File.separator.concat(packageName.replace("\\.", File.separator)))
                .concat(File.separatorChar + StringUtils.upperCaseFirstChar(beanName) + ".java");
    }

    /**
     * raise the beaner
     *
     * @param param param
     * @return beaner
     */
    protected abstract Beaner raiseBeaner(String param);

}
